package com.iotimc.attendancesystem.entity;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * @author david
 * @date 2017/12/4
 */

public class PageHelper<T> {
    private AbstractDao dao;
    private QueryBuilder queryBuilder;
    private int perPage = 10; // 每页条目
    private int currentPage = 1;// 当前页
    private int pageNum = 1; // 页码
    private int count;// 总共条目

    public List getData() {
        if (dao != null) {
            return dao.queryBuilder()
                    .offset((currentPage - 1) * perPage).limit(perPage).list();
        } else {
            return getQueryData();
        }
    }

    public void setQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
        this.dao = null;
        setCount((int) queryBuilder.count());
    }

    private List getQueryData() {
        return queryBuilder.offset((currentPage - 1) * perPage).limit(perPage).list();
    }

    public void setDao(AbstractDao dao) {
        this.dao = dao;
        this.queryBuilder = null;
        setCount((int) dao.count());
    }

    public PageHelper(int perPage) {
        this.perPage = perPage;
    }

    public void setCount(int count) {
        this.count = count;
        pageNum = count % perPage == 0 ? (count / perPage) : (count / perPage + 1);
    }

    public int getCount() {
        return this.count;
    }

    public int getCurrentPage() {
        return this.currentPage;
    }

    public void setCurrentPage(int currentPage){
        this.currentPage = currentPage;
    }
    public int getPageNum() {
        return this.pageNum;
    }

    public int getPerPage() {
        return this.perPage;
    }

    public void gotoPage(int n) { // 页面跳转
        currentPage = n > pageNum ? pageNum : (n < 1 ? 1 : n);
    }

    public boolean hasNextPage() {// 是否有下一页
        return currentPage < pageNum;
    }

    public boolean hasPrePage() {// 是否有前一页
        return currentPage > 1;
    }

    public void headPage() {// 第一页
        currentPage = 1;
    }

    public void lastPage() {// 最后一页
        currentPage = pageNum;
    }

    public void nextPage() {// 下一页
        currentPage = hasNextPage() ? currentPage + 1 : pageNum;
    }

    public void prePage() {// 前一页
        currentPage = hasPrePage() ? currentPage - 1 : 1;
    }

    public void setPerPage(int perPage) {// 设置上一页面
        this.perPage = perPage;
    }
}
